package com.example.dao.impl;

import com.example.dao.HelpDao;
import com.example.pojo.Help;
import com.example.utils.DBConnection;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository("helpDao")
public class HelpDaoImpl implements HelpDao {
    public List<Help> getHelpList() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Help> helpList = new ArrayList<>();
        try {
            conn = DBConnection.getConnection();
            String sql = "select h_id hId,a_id aId,avatar,title,content,likes,read_times readTimes,publish_time " +
                    "publishTime" +
                    " from " +
                    "help order by publish_time desc limit 5";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()) {
                Integer hId = rs.getInt("hId");
                Integer aId = rs.getInt("aId");
                String avatar = rs.getString("avatar");
                String title = rs.getString("title");
                String content = rs.getString("content");
                Integer likes = rs.getInt("likes");
                Integer readTimes = rs.getInt("readTimes");
                String publishTime = rs.getString("publishTime").substring(0,16);
                Help help = new Help(hId,aId,avatar,title,content,likes,readTimes,publishTime);
                helpList.add(help);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DBConnection.close(rs,ps,conn);
        return helpList;
    }
}
